package com.xzw.cameratest;


import static com.xzw.cameratest.activty.PlayOnlineActivity.coverEncryptKey;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.business.adapter.DataAdapterImpl;
import com.android.business.adapter.DataAdapterInterface;
import com.android.business.entity.ChannelInfo;
import com.android.business.entity.EnvironmentInfo;
import com.android.business.entity.GroupInfo;
import com.android.business.entity.LoginType;
import com.android.business.entity.UserInfo;
import com.android.business.entity.VictoryKey;
import com.android.business.exception.BusinessException;
import com.android.dahua.dhplaycomponent.IMediaPlayListener;
import com.android.dahua.dhplaycomponent.IOperationListener;
import com.android.dahua.dhplaycomponent.IPTZListener;
import com.android.dahua.dhplaycomponent.ITalkListener;
import com.android.dahua.dhplaycomponent.PlayManagerProxy;
import com.android.dahua.dhplaycomponent.audiotalk.param.CloudBaseTalk;
import com.android.dahua.dhplaycomponent.audiotalk.param.DPSTalk;
import com.android.dahua.dhplaycomponent.audiotalk.param.ExpressTalk;
import com.android.dahua.dhplaycomponent.audiotalk.param.TalkParam;
import com.android.dahua.dhplaycomponent.audiotalk.param.inner.CloudBaseTalkParam;
import com.android.dahua.dhplaycomponent.audiotalk.param.inner.DPSTalkParam;
import com.android.dahua.dhplaycomponent.audiotalk.param.inner.ExpressTalkParam;
import com.android.dahua.dhplaycomponent.camera.RTCamera.CloudBaseRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.CloudBaseRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.RTCamera.DPSRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.DPSRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.RTCamera.ExpressRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.ExpressRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.inner.Camera;
import com.android.dahua.dhplaycomponent.camera.inner.RealInfo;
import com.android.dahua.dhplaycomponent.common.Err;
import com.android.dahua.dhplaycomponent.common.PlayStatusType;
import com.android.dahua.dhplaycomponent.common.PtzOperation;
import com.android.dahua.dhplaycomponent.common.PtzZoomState;
import com.android.dahua.dhplaycomponent.common.RecordType;
import com.android.dahua.dhplaycomponent.common.TalkResultType;
import com.android.dahua.dhplaycomponent.windowcomponent.entity.ControlType;
import com.android.dahua.dhplaycomponent.windowcomponent.window.PlayWindow;
import com.dahua.permission.PermissionUtil;
import com.dahua.permission.constant.PermissionConstant;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.orhanobut.logger.Logger;
import com.xzw.cameratest.adapter.OrganizationTreeAdapter;
import com.xzw.cameratest.app.InfoBean;
import com.xzw.cameratest.app.ToastUtils;
import com.xzw.cameratest.async.AsyncBuilder;
import com.xzw.cameratest.base.BaseActivity;
import com.xzw.cameratest.bean.Node;
import com.xzw.cameratest.common.CommonInfo;
import com.xzw.cameratest.common.Config;
import com.xzw.cameratest.organization.GroupLoadManager;
import com.xzw.cameratest.utils.CheckedUtil;
import com.xzw.cameratest.utils.FileStorageUtil;
import com.xzw.cameratest.utils.SPUtils;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends BaseActivity implements PermissionUtil.OnPermissionRequestListener {
    static {
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("dslalien");
        System.loadLibrary("dsl");
        System.loadLibrary("CommonSDK");
        System.loadLibrary("DPRTSPSDK");
        System.loadLibrary("DPExpressStream");
        System.loadLibrary("RtpOUdpStream");

    }

    String mUuid = "";

    private Context mContext = this;
    //    @BindView(R.id.ptz_top_btn)
//    ImageButton ptzTopBtn;
//    @BindView(R.id.ptz_left_btn)
//    ImageButton ptzLeftBtn;
//    @BindView(R.id.ptz_flip_btn)
//    ImageButton ptzFlipBtn;
//    @BindView(R.id.ptz_right_btn)
//    ImageButton ptzRightBtn;
//    @BindView(R.id.ptz_bottom_btn)
//    ImageButton ptzBottomBtn;
    @BindView(R.id.ptz_control_ly)
    LinearLayout ptzControlLy;
    @BindView(R.id.hd_video)
    TextView hdVideo;
    @BindView(R.id.fluent_video)
    TextView fluentVideo;
    TextView focal_length_plus;
    TextView focal_length_reduce;
    @BindView(R.id.ic_play)
    TextView icPlay;
    @BindView(R.id.ic_pause)
    TextView icPause;
    @BindView(R.id.ic_take_photo)
    TextView icTakePhoto;
    @BindView(R.id.ic_pic)
    TextView icPic;
    @BindView(R.id.ic_voice)
    TextView icVoice;
    @BindView(R.id.ic_no_voice)
    TextView icNoVoice;
    @BindView(R.id.imgbutton_visable)
    ImageView imgbutton_visable;

    @BindView(R.id.linear_right)
    LinearLayout linear_right;
    @BindViews({R.id.radio1, R.id.radio2, R.id.radio3, R.id.radio4})
    List<CheckBox> radios; // 单选组
    //    @BindView(R.id.ic_no_voice)
//    ImageView    image_is_viaable;
//    @BindView(R.id.ic_yuntai)
//    ImageView ic_yuntai;
    @BindView(R.id.linear_yuntai_control)
    LinearLayout linear_yuntai_control;

    @BindView(R.id.linear_yuntai_is_visable)
    LinearLayout linear_yuntai_is_visable;

    @BindView(R.id.linear_yuntai_fun_isvisable)
    LinearLayout linear_yuntai_fun_isvisable;
//    @BindView(R.id.tv_visable)
//    TextView tv_visable;

//    @BindView(R.id.iv_full_screen)
//    ImageView iv_full_screen;
//    @BindView(R.id.linear_yuntai_visable)
//    LinearLayout linear_yuntai_visable;

    //    @BindView(R.id.bottm_control)
//    LinearLayout bottm_control;
    @BindView(R.id.linear_title)
    LinearLayout linear_title;


    @BindView(R.id.linear1)
    LinearLayout linear1;
    @BindView(R.id.linear2)
    LinearLayout linear2;
    @BindView(R.id.linear3)
    LinearLayout linear3;
    @BindView(R.id.linear4)
    LinearLayout linear4;


    @BindView(R.id.playWindow1)
    PlayWindow playWindow1;
    @BindView(R.id.playWindow2)
    PlayWindow playWindow2;
    @BindView(R.id.playWindow3)
    PlayWindow playWindow3;
    @BindView(R.id.playWindow4)
    PlayWindow playWindow4;


    private ImageButton ptz_top_btn, ptz_left_btn, ptz_right_btn, ptz_bottom_btn;
    private int isVisable = 1;
    private int isVisable_right = 1;

    private String TAG = "MainActivity";

    /********
     *
     *    频道列表
     * @return
     */

//    private RecyclerView recyclerView;
//    private OrganizationTreeAdapter adapter;
    private List<Node> mVisibleNodes = new ArrayList<>();

    /*****
     *   播放
     * @return
     */
    protected PlayManagerProxy mPlayManager1, mPlayManager2, mPlayManager3, mPlayManager4;
    private PermissionUtil permissionUtil;
    //    private int mScreenHeight;
//    private int mScreenWidth;
    private int mPermission;
    private boolean isFull = false;
    public static final int Stream_Assist_Type = 2;        //辅码流 // auxiliary stream
    //    public static final int Stream_Third_Type = 3;
    private DataAdapterInterface dataAdapterInterface;


    private ChannelInfo channelInfo1, channelInfo2, channelInfo3, channelInfo4;
    private List<ChannelInfo> channelInfoList = new ArrayList<>();


    private String encryptKey = "";


    /******
     *   设置播放监听
     */
    public static final int KEY_Handler_Stream_Played = 1;
    public static final int KEY_Handler_First_Frame = 2;
    public static final int KEY_Handler_Net_Error = 3;
    public static final int KEY_Handler_Play_Failed = 4;
    private boolean isPlaying = false;

    protected String[] recordPath;
    private boolean isStartTalk = false;


    @SuppressLint("HandlerLeak")
    protected Handler mPlayOnlineHander = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Played:
                    isPlaying = true;
                    int winIndex = (Integer) msg.obj;

                    if (winIndex != mPlayManager1.getSelectedWindowIndex()) return;
                    if (channelInfoList != null && channelInfoList.size() == 1) {
                        mPlayManager1.maximizeWindow(winIndex);
                        mPlayManager1.setEZoomEnable(winIndex, true);
                    }
//                    if (mPlayManager.isNeedOpenAudio(winIndex))
                    openAudio(winIndex);
                    break;
                case KEY_Handler_First_Frame:
                    mPlayManager1.playCurpage();
                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                    isPlaying = false;
                    winIndex = (Integer) msg.obj;
                    stopPlay(winIndex);
                    break;
            }
        }
    };


    @SuppressLint("HandlerLeak")
    protected Handler mPlayOnlineHander2 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Played:
                    isPlaying = true;
                    int winIndex = (Integer) msg.obj;

                    if (winIndex != mPlayManager2.getSelectedWindowIndex()) return;
                    if (channelInfoList != null && channelInfoList.size() == 1) {
                        mPlayManager2.maximizeWindow(winIndex);
                        mPlayManager2.setEZoomEnable(winIndex, true);
                    }
//                    if (mPlayManager.isNeedOpenAudio(winIndex))
                    openAudio(winIndex);
                    break;
                case KEY_Handler_First_Frame:
                    mPlayManager2.playCurpage();
                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                    isPlaying = false;
                    winIndex = (Integer) msg.obj;
                    stopPlay(winIndex);
                    break;
            }
        }
    };


    @SuppressLint("HandlerLeak")
    protected Handler mPlayOnlineHander3 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Played:
                    isPlaying = true;
                    int winIndex = (Integer) msg.obj;

                    if (winIndex != mPlayManager3.getSelectedWindowIndex()) return;
                    if (channelInfoList != null && channelInfoList.size() == 1) {
                        mPlayManager3.maximizeWindow(winIndex);
                        mPlayManager3.setEZoomEnable(winIndex, true);
                    }
//                    if (mPlayManager.isNeedOpenAudio(winIndex))
                    openAudio(winIndex);
                    break;
                case KEY_Handler_First_Frame:
                    mPlayManager3.playCurpage();
                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                    isPlaying = false;
                    winIndex = (Integer) msg.obj;
                    stopPlay(winIndex);
                    break;
            }
        }
    };
    @SuppressLint("HandlerLeak")
    protected Handler mPlayOnlineHander4 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Played:
                    isPlaying = true;
                    int winIndex = (Integer) msg.obj;

                    if (winIndex != mPlayManager4.getSelectedWindowIndex()) return;
                    if (channelInfoList != null && channelInfoList.size() == 1) {
                        mPlayManager4.maximizeWindow(winIndex);
                        mPlayManager4.setEZoomEnable(winIndex, true);
                    }
//                    if (mPlayManager.isNeedOpenAudio(winIndex))
                    openAudio(winIndex);
                    break;
                case KEY_Handler_First_Frame:
                    mPlayManager4.playCurpage();
                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                    isPlaying = false;
                    winIndex = (Integer) msg.obj;
                    stopPlay(winIndex);
                    break;
            }
        }
    };


    public interface OnR {
        public void getMsg(List<ChannelInfo> channelInfoList);
    }


    public static OnR onR;


    public interface OnR1 {
        public void getMsg();
    }


    public static OnR1 onR1;

    @Override
    protected int initContentView() {
        return R.layout.activity_main;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {

        ptz_top_btn = findViewById(R.id.ptz_top_btn);
        ptz_right_btn = findViewById(R.id.ptz_right_btn);
        ptz_left_btn = findViewById(R.id.ptz_left_btn);
        ptz_bottom_btn = findViewById(R.id.ptz_bottom_btn);

//        mPlayWindow = findViewById(R.id.playWindow);

        focal_length_plus = findViewById(R.id.focal_length_plus);
        focal_length_reduce = findViewById(R.id.focal_length_reduce);


        ptz_top_btn.setOnTouchListener(mOnTouchListener);
        ptz_bottom_btn.setOnTouchListener(mOnTouchListener);
        ptz_left_btn.setOnTouchListener(mOnTouchListener);
        ptz_right_btn.setOnTouchListener(mOnTouchListener);

        focal_length_plus.setOnTouchListener(mOnTouchListener);
        focal_length_reduce.setOnTouchListener(mOnTouchListener);

//        adapter = new OrganizationTreeAdapter(mContext, mVisibleNodes);
//        recyclerView = findViewById(R.id.recycler_view);
//        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//        recyclerView.setAdapter(adapter);
//        adapter.setOnItemClickListener(new OrganizationTreeAdapter.OnItemClickListener() {
//            @Override
//            public void onClick(int position) {
////                expandOrCollapse(0);
////                new Thread(new Runnable() {
////                    @Override
////                    public void run() {
////                        try {
////                            Thread.sleep(2000);
////                            handler.sendEmptyMessage(0);
////                        } catch (InterruptedException e) {
////                            // TODO Auto-generated catch block
////                            e.printStackTrace();
////                        }
////                    }
////                }).start();
//
//
////                Node node = mVisibleNodes.get(position);
////                if (node.getData() instanceof ChannelInfo) {
////                    onClickChannelNode((ChannelInfo) node.getData());
//////                    Log.e("列表", "ChannelInfo=" + ((GroupInfo) node.getData()).getGroupName());
////                } else if (node.getData() instanceof GroupInfo) {
////                    expandOrCollapse(position);
////                    Log.e("列表", "GroupInfo的position=" + position);
////                    Log.e("列表", "GroupInfo=" + ((GroupInfo) node.getData()).getGroupName());
////                    OkHttpClient client = new OkHttpClient.Builder().build();
////                    Request request = new Request.Builder().url("http://baihu.citymishu.com:8441/fuwuqi/wangye/" + ((GroupInfo) node.getData()).getGroupName() + ".txt").build();
////                    Log.d("OkHttp", "http://baihu.citymishu.com:8441/fuwuqi/wangye/" + ((GroupInfo) node.getData()).getGroupName() + ".txt");
////                    client.newCall(request).enqueue(new Callback() {
////                        @Override
////                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
////
////                        }
////
////                        @Override
////                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
////                            String str = response.body().string();
////                            Log.d("OkHttp", "str=" + str);
////                            if (!str.contains("删除")) {
////                                Log.d("OkHttp", "str=" + str);
////                                InfoBean infoBean = new InfoBean();
////                                InfoBean infoBean1 = infoBean.objectFromData(str);
////
////                                Log.d("OkHttp", "infoBean1.get井号()=" + infoBean1.get井号());
////                                MainActivity.this.runOnUiThread(new Runnable() {
////                                    @Override
////                                    public void run() {
////                                        if (!str.contains("删除")) {
////                                            tv_info.setText(infoBean1.get小队名称());
////                                            tv_info_name.setText(infoBean1.get联系人());
////                                            tv_info_tel.setText(infoBean1.get联系电话());
////                                            tv_info_gongxu.setText(infoBean1.get工序());
////                                            tv_info_jinghao.setText(infoBean1.get井号());
////                                        }
////                                    }
////                                });
////                            }
////
////
////                        }
////                    });
////                }
//            }
//        });
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            expandOrCollapse(7);
        }
    };

    int streamtype = 0;// ，0：主码流，1：辅码流
    String channelInfoName;

    public void onClickChannelNode(ChannelInfo channelInfo) {
//        showToast(channelInfo.getName());
//        this.mChannelInfo = channelInfo;
//        permissionUtil = new PermissionUtil(this);
//        dataAdapterInterface = DataAdapterImpl.getInstance();
//        mPlayManager = new PlayManagerProxy();
//        //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
//        mPlayManager.init(this,  mPlayWindow);
//        //设置播放监听
//        // set play monitor.
//        mPlayManager.setOnMediaPlayListener(iMediaPlayListener);
//        //设置窗口操作监听
//        mPlayManager.setOnOperationListener(iOperationListener);
//
//        // set the intercom monitor.
//        mPlayManager.setOnTalkListener(new ITalkListener());
//        mPlayManager.setLogEnable(true);
//        //设置云台监听
//        // set the cloud monitor.
//        mPlayManager.setOnPTZListener(iptzListener);
//        channelInfoList.add(mChannelInfo);
//
//        mPlayManager.addCameras(getCameras(streamtype));
//        mPlayManager.playCurpage();
//
//
//        //判断设备是否支持云台功能
////        linear_yuntai_control.setVisibility(mChannelInfo.getCameraInputInfo() != null && mChannelInfo.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.GONE);
//        linear_yuntai_visable.setVisibility(mChannelInfo.getCameraInputInfo() != null && mChannelInfo.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.INVISIBLE);
//
//        //选择频道后自动刷新
//        channelInfoList.clear();
//        adapter.notifyDataSetChanged();
//        loadGroup();
//
//        bottm_control.setVisibility(View.VISIBLE);


    }

    @Override
    protected void onResume() {
        super.onResume();
        replay();
    }

    private List<Camera> getCameras() {
        List<Camera> cameras = new ArrayList<>();
        if (channelInfoList != null) {
            Log.e("MainActivity", "channelInfoList=" + channelInfoList.size());
            for (ChannelInfo channelInfo : channelInfoList) {
                cameras.add(getCamera(channelInfo, streamtype));
            }
        }
        Log.e("MainActivity", "cameras个数=" + channelInfoList.size());

        return cameras;
    }

    private List<Camera> getCameras(int streamtype) {
        List<Camera> cameras = new ArrayList<>();
        if (channelInfoList != null) {
            Log.e("MainActivity", "channelInfoList=" + channelInfoList.size());
            for (ChannelInfo channelInfo : channelInfoList) {
                cameras.add(getCamera(channelInfo, streamtype));
            }
        }
        Log.e("MainActivity", "cameras个数=" + channelInfoList.size());

        return cameras;
    }

    private Camera getCamera(ChannelInfo channelInfo, int streamtype) {

        getEncryptKey(channelInfo);
        ExpressRTCameraParam expressRTCameraParam = new ExpressRTCameraParam();
        expressRTCameraParam.setCameraID(channelInfo.getChnSncode());


        expressRTCameraParam.setStreamType(streamtype);

        int mStreamType = ChannelInfo.ChannelStreamType.getValue(channelInfo.getStreamType());
        if (mStreamType > Stream_Assist_Type) {
            mStreamType = Stream_Assist_Type;
        }
        expressRTCameraParam.setStreamType(mStreamType);
        expressRTCameraParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
        expressRTCameraParam.setServerIP(SPUtils.getString(Config.IP, ""));
        expressRTCameraParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));

        if (!TextUtils.isEmpty(encryptKey)) {
            expressRTCameraParam.setEncrypt(true);
            expressRTCameraParam.setPsk(encryptKey);
        }
        expressRTCameraParam.setAuthorization(CommonInfo.getInstance().getEnvironmentInfo().getAuthorization());
        expressRTCameraParam.setUri("/evo-apigw/admin/API/MTS/Video/");
        expressRTCameraParam.setLocation("");
        expressRTCameraParam.setUser_client(6);
        expressRTCameraParam.setUseHttps(CommonInfo.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);

        return new ExpressRTCamera(expressRTCameraParam);
    }

    /**
     * 获取当前设备使用的码流加密秘钥
     */
    private void getEncryptKey(ChannelInfo mChannelInfo) {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<VictoryKey>() {
            @Override
            public VictoryKey doInBackground() throws Exception {
                VictoryKey victoryKey = dataAdapterInterface.getCurrentMediaVK(mChannelInfo.getChnSncode().substring(0, mChannelInfo.getChnSncode().indexOf("$")));
                if (victoryKey != null)
                    encryptKey = coverEncryptKey(victoryKey.getVkId(), victoryKey.getVkValue());
                return victoryKey;
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<VictoryKey>() {
            @Override
            public void onSuccess(VictoryKey victoryKey) {

            }

            @Override
            public void onError(BusinessException e) {

            }
        });
    }


    private void expandOrCollapse(int position) {
        Node node = mVisibleNodes.get(position);
        node.setExpand(!node.isExpand());
        if (!node.isLoadChannel()) {
            GroupInfo groupInfo = (GroupInfo) node.getData();
            loadChannel(node, groupInfo.getChannelList());
        } else {
            refreshVisibleNode();
        }
    }

    @Override
    protected void initData() {
        onR = new OnR() {
            @Override
            public void getMsg(List<ChannelInfo> channelInfoListNew) {

                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            channelInfoList = channelInfoListNew;

                            Thread.sleep(1000);
                            handler2.sendEmptyMessage(0);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }).start();
            }
        };
    }

    @SuppressLint("HandlerLeak")
    private Handler handler2 = new Handler() {


        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);


            permissionUtil = new PermissionUtil(MainActivity.this);
            dataAdapterInterface = DataAdapterImpl.getInstance();


            /****
             * \
             *   第一个窗口
             */

            mPlayManager1 = new PlayManagerProxy();
            //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
            mPlayManager1.init(MainActivity.this, playWindow1);
            //设置播放监听
            // set play monitor.
            mPlayManager1.setOnMediaPlayListener(iMediaPlayListener);
            //设置窗口操作监听
            mPlayManager1.setOnOperationListener(iOperationListener);
            // set the intercom monitor.
            mPlayManager1.setOnTalkListener(new ITalkListener());
            mPlayManager1.setLogEnable(true);
            //设置云台监听
            // set the cloud monitor.
            mPlayManager1.setOnPTZListener(iptzListener1);


            /****
             * \
             *   第二个窗口
             */

            mPlayManager2 = new PlayManagerProxy();
            //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
            mPlayManager2.init(MainActivity.this, playWindow2);
            //设置播放监听
            // set play monitor.
            mPlayManager2.setOnMediaPlayListener(iMediaPlayListener2);
            //设置窗口操作监听
            mPlayManager2.setOnOperationListener(iOperationListener2);
            // set the intercom monitor.
            mPlayManager2.setOnTalkListener(new ITalkListener());
            mPlayManager2.setLogEnable(true);
            //设置云台监听
            // set the cloud monitor.
            mPlayManager2.setOnPTZListener(iptzListener2);


            /****
             * \
             *   第三个窗口
             */

            mPlayManager3 = new PlayManagerProxy();
            //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
            mPlayManager3.init(MainActivity.this, playWindow3);
            //设置播放监听
            // set play monitor.
            mPlayManager3.setOnMediaPlayListener(iMediaPlayListener3);
            //设置窗口操作监听
            mPlayManager3.setOnOperationListener(iOperationListener3);
            // set the intercom monitor.
            mPlayManager3.setOnTalkListener(new ITalkListener());
            mPlayManager3.setLogEnable(true);
            //设置云台监听
            // set the cloud monitor.
            mPlayManager3.setOnPTZListener(iptzListener3);

            /****
             * \
             *   第四个窗口
             */

            mPlayManager4 = new PlayManagerProxy();
            //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
            mPlayManager4.init(MainActivity.this, playWindow4);
            //设置播放监听
            // set play monitor.
            mPlayManager4.setOnMediaPlayListener(iMediaPlayListener4);
            //设置窗口操作监听
            mPlayManager4.setOnOperationListener(iOperationListener4);
            // set the intercom monitor.
            mPlayManager4.setOnTalkListener(new ITalkListener());
            mPlayManager4.setLogEnable(true);
            //设置云台监听
            // set the cloud monitor.
            mPlayManager4.setOnPTZListener(iptzListener4);


            channelInfo1 = channelInfoList.get(0);
            channelInfo2 = channelInfoList.get(1);
            channelInfo3 = channelInfoList.get(2);
            channelInfo4 = channelInfoList.get(3);


            channelInfoList.clear();
            channelInfoList.add(channelInfo1);
            mPlayManager1.addCameras(getCameras());
            mPlayManager1.playCurpage();


            channelInfoList.clear();
            channelInfoList.add(channelInfo2);
            mPlayManager2.addCameras(getCameras());
            mPlayManager2.playCurpage();


            channelInfoList.clear();
            channelInfoList.add(channelInfo3);
            mPlayManager3.addCameras(getCameras());
            mPlayManager3.playCurpage();


            channelInfoList.clear();
            channelInfoList.add(channelInfo4);
            mPlayManager4.addCameras(getCameras());
            mPlayManager4.playCurpage();


            linear1.setVisibility(View.VISIBLE);
            linear2.setVisibility(View.VISIBLE);
            linear3.setVisibility(View.VISIBLE);
            linear4.setVisibility(View.VISIBLE);


        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void doSomething() {

        initEnvironment();
    }

    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionevent) {
            boolean ptz_result = false;
            int action = motionevent.getAction();
//            final int speed = EZConstants.PTZ_SPEED_DEFAULT;
            switch (action) {
                case MotionEvent.ACTION_DOWN:// 手指按下
                    switch (view.getId()) {

                        case R.id.ptz_top_btn:// 云台-上
                            Log.i(TAG, "ACTION_DOWN上");
                            if (checkedValues.equals("rd1")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.up, false, channelInfo1);
                            } else if (checkedValues.equals("rd2")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.up, false, channelInfo2);

                            } else if (checkedValues.equals("rd3")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.up, false, channelInfo3);

                            } else if (checkedValues.equals("rd4")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.up, false, channelInfo4);
                            }

                            break;
                        case R.id.ptz_bottom_btn:// 云台-下
                            Log.i(TAG, "ACTION_DOWN下");

                            if (checkedValues.equals("rd1")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.down, false, channelInfo1);
                            } else if (checkedValues.equals("rd2")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.down, false, channelInfo2);

                            } else if (checkedValues.equals("rd3")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.down, false, channelInfo3);

                            } else if (checkedValues.equals("rd4")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.down, false, channelInfo4);
                            }
                            break;
                        case R.id.ptz_left_btn:// 云台-左
                            Log.i(TAG, "ACTION_DOWN左");

                            if (checkedValues.equals("rd1")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.left, false, channelInfo1);
                            } else if (checkedValues.equals("rd2")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.left, false, channelInfo2);
                            } else if (checkedValues.equals("rd3")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.left, false, channelInfo3);
                            } else if (checkedValues.equals("rd4")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.left, false, channelInfo4);
                            }
                            break;
                        case R.id.ptz_right_btn:// 云台-右
                            Log.i(TAG, "ACTION_DOWN右");
                            if (checkedValues.equals("rd1")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.right, false, channelInfo1);
                            } else if (checkedValues.equals("rd2")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.right, false, channelInfo2);
                            } else if (checkedValues.equals("rd3")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.right, false, channelInfo3);
                            } else if (checkedValues.equals("rd4")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.right, false, channelInfo4);
                            }
                            break;
                        case R.id.focal_length_plus://焦距+
                            Log.i(TAG, "ACTION_DOWN焦距+");
                            if (checkedValues.equals("rd1")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, false, channelInfo1);
                            } else if (checkedValues.equals("rd2")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, false, channelInfo2);
                            } else if (checkedValues.equals("rd3")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, false, channelInfo3);
                            } else if (checkedValues.equals("rd4")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, false, channelInfo4);
                            }
                            break;
                        case R.id.focal_length_reduce://焦距-
                            Log.i(TAG, "ACTION_DOWN焦距-");
                            if (checkedValues.equals("rd1")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, false, channelInfo1);
                            } else if (checkedValues.equals("rd2")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, false, channelInfo2);

                            } else if (checkedValues.equals("rd3")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, false, channelInfo3);

                            } else if (checkedValues.equals("rd4")) {
                                sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, false, channelInfo4);
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case MotionEvent.ACTION_UP:// 手指抬起
                    switch (view.getId()) {

                        case R.id.ptz_top_btn:
                            Log.i(TAG, "ACTION_UP上");
                            break;
                        case R.id.ptz_bottom_btn:
                            Log.i(TAG, "ACTION_UP下");
                            break;
                        case R.id.ptz_left_btn:
                            Log.i(TAG, "ACTION_UP左");
                            break;
                        case R.id.ptz_right_btn:
                            Log.i(TAG, "ACTION_UP右");
                            break;
                        case R.id.focal_length_plus://焦距+
                            Log.i(TAG, "ACTION_DOWN焦距+");
                            sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, true, channelInfo1);
                            break;
                        case R.id.focal_length_reduce://焦距-
                            Log.i(TAG, "ACTION_DOWN焦距-");
                            sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, true, channelInfo1);
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    /**
     * 登录
     */
    private void login() {
        final String username = "TEST";
        final String password = "Admin123";
        final String ip = "124.160.33.135";
        final String port = "4077";

        showProgressDialog("登录中...");
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<UserInfo>() {
            @Override
            public UserInfo doInBackground() throws Exception {
                if (TextUtils.isEmpty(mUuid)) {
                    mUuid = UUID.randomUUID().toString();
                    SPUtils.saveString(Config.UUID, mUuid);
                }
                DataAdapterImpl.getInstance().initServer(ip, Integer.parseInt(port));
                return DataAdapterImpl.getInstance().login(username, password, "1", mUuid, LoginType.TYPE_APP_CHINESE, 0);
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<UserInfo>() {
            @Override
            public void onSuccess(UserInfo userInfo) {

                CommonInfo.getInstance().setUserInfo(userInfo);
                CommonInfo.getInstance().saveLoginData(ip, port, username, password);
                SPUtils.saveString(Config.GROUP_ID, getGroupIdFromUserInfo(userInfo));
                dismissProgressDialog();
                loadGroup();
            }

            @Override
            public void onError(com.android.business.exception.BusinessException e) {
                dismissProgressDialog();
                showToast("登录失败...");
            }
        });
    }

    private void loadGroup() {

        AsyncBuilder.createTask(new AsyncBuilder.BusinessNullRetTask() {
            @Override
            public void doInBackground() throws Exception {
                GroupLoadManager.getInstance().loadGroup();
            }
        }).loading(new AsyncBuilder.LoadingListener() {
            @Override
            public void beginLoading() {
                showProgressDialog();
            }

            @Override
            public void finishLoading() {
                dismissProgressDialog();


            }
        }).resultInMain(this, new AsyncBuilder.ResultNullListener() {
            @Override
            public void onSuccess() {
                refreshVisibleNode();

                expandOrCollapse(0);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            handler.sendEmptyMessage(0);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            @Override
            public void onError(BusinessException e) {
                showToast(getString(R.string.organization_tree_organization_load_fail));
            }
        });
    }

    private void refreshVisibleNode() {
        mVisibleNodes.clear();
        mVisibleNodes.addAll(filterVisibleNode());
//        adapter.notifyDataSetChanged();

//        expandOrCollapse(0);
    }

    private List<Node> filterVisibleNode() {
        List<Node> result = new ArrayList<>();
        for (Node node : GroupLoadManager.getInstance().getAllNodes()) {
            if (node.isRoot() || node.isParentExpand()) {
                result.add(node);
            }
        }
        return result;
    }

    private String getGroupIdFromUserInfo(UserInfo userInfo) {
        Object groupId = userInfo.getExtandAttributeValue("groupId");
        String strGroupID = "";
        if (groupId instanceof String) {
            strGroupID = (String) groupId;
        } else if (groupId instanceof Long) {
            strGroupID = groupId.toString();
        }
        return strGroupID;
    }

    private void initEnvironment() {
        try {
            //初始化平台SDK
            DataAdapterImpl.getInstance().createDataAdapter(BuildConfig.sdkPackage);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        SPUtils.init(getApplicationContext());
        EnvironmentInfo environmentInfo = new EnvironmentInfo();
        //设置是否使用https请求
        environmentInfo.setHttps(true);
        try {
            //设置当前版本名称 VersionName
            environmentInfo.setVersionName(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //设置当前语言
        environmentInfo.setLanguage(getResources().getConfiguration().locale.getLanguage());
        environmentInfo.setApplication(getApplication());
        //设置当前客户端类型 （选填）
        environmentInfo.setClientType("Android");
        try {
            DataAdapterImpl.getInstance().initEnvironmentInfo(environmentInfo);
            CommonInfo.getInstance().setEnvironmentInfo(environmentInfo);
        } catch (BusinessException e) {
            e.printStackTrace();
        }

        login();

    }


    @OnClick({

            R.id.hd_video, R.id.fluent_video,
            R.id.focal_length_plus, R.id.focal_length_reduce,
            R.id.ic_play, R.id.ic_pause, R.id.ic_take_photo, R.id.ic_pic, R.id.ic_voice,
            R.id.ic_no_voice

            , R.id.image_is_viaable, R.id.imgbutton_visable

    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.hd_video:  //高清

//                mPlayManager.addCameras(getCameras(0));
//                mPlayManager.playCurpage();
                break;
            case R.id.fluent_video:  //流畅
//                mPlayManager.addCameras(getCameras(1));
//                mPlayManager.playCurpage();
                break;
            case R.id.focal_length_plus:  //焦距+
                break;
            case R.id.focal_length_reduce:  //焦距-
                break;
            case R.id.ic_play://开始录制
                checkPermission(2);
                break;
            case R.id.ic_pause: //停止录制
                checkPermission(4);
                break;
            case R.id.ic_take_photo:  //违规抓拍
                checkPermission(1);
                break;
            case R.id.ic_pic:  //抓拍图片
                checkPermission(6);
                break;
            case R.id.ic_voice:   //开启喊话
                checkPermission(3);
                break;
            case R.id.ic_no_voice:   //停止喊话
                checkPermission(5);

                break;

//            case R.id.ic_yuntai:
            //默认不显示 点击按钮才显示 同时字变成 隐藏云台
//                isVisable++;
//                if (isVisable % 2 != 0) {
//                    linear_yuntai_control.setVisibility(View.GONE);
//                    tv_visable.setText("显示云台");
//
//                } else {//点击了单数次
//                    linear_yuntai_control.setVisibility(View.VISIBLE);
//                    tv_visable.setText("隐藏云台");
//                }
//                break;

//            case R.id.iv_full_screen:
//                switchScreen();
//                break;

            case R.id.image_is_viaable:
                //默认不显示 点击按钮才显示 同时字变成 隐藏云台
                isVisable++;
                if (isVisable % 2 != 0) {
                    linear_yuntai_control.setVisibility(View.GONE);


                } else {//点击了单数次
                    linear_yuntai_control.setVisibility(View.VISIBLE);

                }
                break;

            case R.id.imgbutton_visable:
                isVisable_right++;
                if (isVisable_right % 2 != 0) {
                    linear_right.setVisibility(View.GONE);
                    imgbutton_visable.setBackground(getResources().getDrawable(R.mipmap.ic_linear_gone));
                } else {//点击了单数次
                    linear_right.setVisibility(View.VISIBLE);
                    imgbutton_visable.setBackground(getResources().getDrawable(R.mipmap.ic_linear_visable));

                }
                break;
            default:
                break;
        }
    }

    /**
     * 单选项点击事件
     *
     * @param checkBox
     */
    String checkedValues;

    @OnClick({R.id.radio1, R.id.radio2, R.id.radio3, R.id.radio4})
    void changeRadios(CheckBox checkBox) {
        CheckedUtil.unCheck(radios);
        checkBox.setChecked(true);

        // 显示选中项值
        checkedValues = CheckedUtil.getOne(radios);
        Log.e("MainActivity", "选中了：" + checkedValues);
        if (linear_yuntai_is_visable != null && channelInfo1 != null && channelInfo2 != null && channelInfo3 != null && channelInfo4 != null) {
            linear_yuntai_fun_isvisable.setVisibility(View.VISIBLE);

            if (checkedValues.equals("rd1")) {
                linear_yuntai_is_visable.setVisibility(channelInfo1.getCameraInputInfo() != null && channelInfo1.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.GONE);
            } else if (checkedValues.equals("rd2")) {
                linear_yuntai_is_visable.setVisibility(channelInfo2.getCameraInputInfo() != null && channelInfo2.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.GONE);

            } else if (checkedValues.equals("rd3")) {
                linear_yuntai_is_visable.setVisibility(channelInfo3.getCameraInputInfo() != null && channelInfo3.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.GONE);

            } else if (checkedValues.equals("rd4")) {
                linear_yuntai_is_visable.setVisibility(channelInfo4.getCameraInputInfo() != null && channelInfo4.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.GONE);

            }
        } else {

            showToast("请稍后选择");
        }


    }

    /**
     * 检查权限
     */
    private void checkPermission(int permissionType) {
        mPermission = permissionType;
        List<String> permissionList = new ArrayList<>();
        switch (permissionType) {
            case 1:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                break;
            case 4:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
            case 2:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
            case 3:
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
                break;
            case 5:
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
                break;
            case 6:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));


        }
        permissionUtil.requestPermissions(this, permissionList.toArray(new String[0]));
    }

    @Override
    public void onPermissionGranted() {
        switch (mPermission) {
            case 1:
                if (checkedValues.equals("rd1")) {
                    onClickCapture(mPlayManager1);
                } else if (checkedValues.equals("rd2")) {
                    onClickCapture(mPlayManager2);
                } else if (checkedValues.equals("rd3")) {
                    onClickCapture(mPlayManager3);
                } else if (checkedValues.equals("rd4")) {
                    onClickCapture(mPlayManager4);
                }
                break;
            case 2:

                if (checkedValues.equals("rd1")) {
                    onClickVideotape(mPlayManager1);
                } else if (checkedValues.equals("rd2")) {
                    onClickVideotape(mPlayManager2);
                } else if (checkedValues.equals("rd3")) {
                    onClickVideotape(mPlayManager3);
                } else if (checkedValues.equals("rd4")) {
                    onClickVideotape(mPlayManager4);
                }
                break;
            case 3:
                if (checkedValues.equals("rd1")) {
                    onClickIntercom(mPlayManager1, channelInfo1);
                } else if (checkedValues.equals("rd2")) {
                    onClickIntercom(mPlayManager2, channelInfo2);
                } else if (checkedValues.equals("rd3")) {
                    onClickIntercom(mPlayManager3, channelInfo3);
                } else if (checkedValues.equals("rd4")) {
                    onClickIntercom(mPlayManager4, channelInfo4);
                }
                break;

            case 4:

                if (checkedValues.equals("rd1")) {
                    onClickStopVideotape(mPlayManager1);
                } else if (checkedValues.equals("rd2")) {
                    onClickStopVideotape(mPlayManager2);
                } else if (checkedValues.equals("rd3")) {
                    onClickStopVideotape(mPlayManager3);
                } else if (checkedValues.equals("rd4")) {
                    onClickStopVideotape(mPlayManager4);
                }

                break;

            case 5:

                if (checkedValues.equals("rd1")) {
                    onClickStopIntercom(mPlayManager1);
                } else if (checkedValues.equals("rd2")) {
                    onClickStopIntercom(mPlayManager2);
                } else if (checkedValues.equals("rd3")) {
                    onClickStopIntercom(mPlayManager3);
                } else if (checkedValues.equals("rd4")) {
                    onClickStopIntercom(mPlayManager4);
                }

                break;

            case 6:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_APP_GALLERY);
                startActivity(intent);


                break;
        }
    }

    /**
     * 抓图
     */
    protected void onClickCapture(PlayManagerProxy mPlayManager) {

        if (!mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex())) return;
        int currentWindowIndex = mPlayManager.getSelectedWindowIndex();
        String path = FileStorageUtil.createSnapPath();
        int ret = mPlayManager1.snapShot(currentWindowIndex, path, true);
        if (ret == Err.OK) {
            showToast(getResources().getString(R.string.screenshots_success) + path);
            MediaScannerConnection.scanFile(this, new String[]{path}, null, null);
        } else {
            showToast(getResources().getString(R.string.screenshots_failed));
        }
    }

    /**
     * 录像
     */
    protected void onClickVideotape(PlayManagerProxy mPlayManager) {

        if (!mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()) || mPlayManager.isPause(mPlayManager.getSelectedWindowIndex()))
            return;
        int currentWindowIndex = mPlayManager.getSelectedWindowIndex();
        recordPath = FileStorageUtil.createRecordPath();
        recordPath[0] = recordPath[0].replaceAll("dav", "mp4");
        int ret = mPlayManager.startRecord(currentWindowIndex, recordPath, RecordType.RECORDER_TYPE_MP4);
        if (ret == Err.OK) {
            showToast(getString(R.string.recording_start));
            MediaScannerConnection.scanFile(getApplicationContext(), recordPath, null, null);
//                mTvVideotape.setSelected(true);
        }

    }

    /**
     * 停止录像
     */
    protected void onClickStopVideotape(PlayManagerProxy mPlayManager) {

        int ret = mPlayManager.stopRecord(mPlayManager.getSelectedWindowIndex());
        if (ret == Err.OK) {
            showToast(getString(R.string.recording_end));
            MediaScannerConnection.scanFile(this, recordPath, null, null);
//                mTvVideotape.setSelected(false);
        }
    }

    /**
     * 对讲
     */
    protected void onClickIntercom(PlayManagerProxy mPlayManager, ChannelInfo mChannelInfo) {
        if (!isPlaying) {
            showToast(getString(R.string.no_intercom_equipment));
            return;
        }
        ExpressTalkParam expressTalkParam = new ExpressTalkParam();
        expressTalkParam.setCameraID(mChannelInfo.getChnSncode().substring(0, mChannelInfo.getChnSncode().indexOf("$")));
        expressTalkParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
        expressTalkParam.setServerIp(SPUtils.getString(Config.IP, ""));
        expressTalkParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));
        expressTalkParam.setAuthorization(CommonInfo.getInstance().getEnvironmentInfo().getAuthorization());
        expressTalkParam.setUri("/evo-apigw/admin/API/MTS/Audio/");
        expressTalkParam.setUser_client(6);
        expressTalkParam.setReset(0);
        expressTalkParam.setTalkType(1);
        expressTalkParam.setTransMode(1);
        expressTalkParam.setSampleRate(TalkParam.AUDIO_SAMPLE_RATE_8000);
        expressTalkParam.setSampleDepth(TalkParam.AUDIO_SAMPLE_DEPTH_16);
        expressTalkParam.setEncodeType(TalkParam.AUDIO_ENCODE_G711A);
        ExpressTalk talk = new ExpressTalk(expressTalkParam);
        mPlayManager.setOnTalkListener(new ITalkListener() {
            @Override
            public void onTalkResult(int winIndex, TalkResultType talkResultType, String code, int type) {

            }
        });
        if (mPlayManager.startTalk(0, talk) == 0) {
            isStartTalk = true;
        } else {
            isStartTalk = false;
            showToast(getString(R.string.intercom_failed));
        }
    }

    /**
     * 停止对讲
     */
    protected void onClickStopIntercom(PlayManagerProxy mPlayManager) {

        if (!isPlaying) {
            showToast(getString(R.string.no_intercom_equipment));
            return;
        }
        isStartTalk = false;
//            mTvIntercom.setSelected(false);
        if (mPlayManager != null) {
            mPlayManager.stopTalk(0);
        }

    }

    @Override
    public void onPermissionDenied() {

    }

    @Override
    public void onPermissionSetting(boolean b) {

    }

    private void loadChannel(final Node parentNode, final List<String> channelIdList) {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessNullRetTask() {
            @Override
            public void doInBackground() throws Exception {
                GroupLoadManager.getInstance().loadChannel(parentNode, channelIdList);
            }
        }).loading(new AsyncBuilder.LoadingListener() {
            @Override
            public void beginLoading() {
                showProgressDialog();
            }

            @Override
            public void finishLoading() {
                dismissProgressDialog();
            }
        }).resultInMain(this, new AsyncBuilder.ResultNullListener() {
            @Override
            public void onSuccess() {
                refreshVisibleNode();
            }

            @Override
            public void onError(BusinessException e) {
                refreshVisibleNode();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        onDestroyPlayManager(mPlayManager1);
        onDestroyPlayManager(mPlayManager2);
        onDestroyPlayManager(mPlayManager3);
        onDestroyPlayManager(mPlayManager4);
    }

    private void onDestroyPlayManager(PlayManagerProxy mPlayManager) {
        if (mPlayManager != null) {
            mPlayManager.unitPlayManager();
            mPlayManager = null;
        }
    }

    /**
     * 开始播放
     */
    private void startPlay(int winIndex, PlayManagerProxy mPlayManager) {
        if (getCameras(streamtype).size() > 0) {
            mPlayManager.addCamera(winIndex, getCameras(streamtype).get(0));
        }
        mPlayManager.playSingle(winIndex);
    }

    /**
     * 重新播放
     */
    private void replay() {
        if (mPlayManager1 != null) {
            mPlayManager1.playCurpage();
        }

    }

    /**
     * 停止播放
     */
    private void stopPlay(int winIndex) {
        mPlayManager1.stopSingle(winIndex);
    }


    private IMediaPlayListener iMediaPlayListener = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, PlayStatusType type, int code) {
            Message msg = Message.obtain();
            msg.obj = winIndex;
            if (type == PlayStatusType.eStreamPlayed) {
                msg.what = KEY_Handler_Stream_Played;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                msg.what = KEY_Handler_First_Frame;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                msg.what = KEY_Handler_Net_Error;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFailed) {
                msg.what = KEY_Handler_Play_Failed;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            }
        }
    };

    private IMediaPlayListener iMediaPlayListener2 = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, PlayStatusType type, int code) {
            Message msg = Message.obtain();
            msg.obj = winIndex;
            if (type == PlayStatusType.eStreamPlayed) {
                msg.what = KEY_Handler_Stream_Played;
                if (mPlayOnlineHander2 != null) mPlayOnlineHander2.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                msg.what = KEY_Handler_First_Frame;
                if (mPlayOnlineHander2 != null) mPlayOnlineHander2.sendMessage(msg);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                msg.what = KEY_Handler_Net_Error;
                if (mPlayOnlineHander2 != null) mPlayOnlineHander2.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFailed) {
                msg.what = KEY_Handler_Play_Failed;
                if (mPlayOnlineHander2 != null) mPlayOnlineHander2.sendMessage(msg);
            }
        }
    };

    private IMediaPlayListener iMediaPlayListener3 = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, PlayStatusType type, int code) {
            Message msg = Message.obtain();
            msg.obj = winIndex;
            if (type == PlayStatusType.eStreamPlayed) {
                msg.what = KEY_Handler_Stream_Played;
                if (mPlayOnlineHander3 != null) mPlayOnlineHander3.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                msg.what = KEY_Handler_First_Frame;
                if (mPlayOnlineHander3 != null) mPlayOnlineHander3.sendMessage(msg);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                msg.what = KEY_Handler_Net_Error;
                if (mPlayOnlineHander3 != null) mPlayOnlineHander3.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFailed) {
                msg.what = KEY_Handler_Play_Failed;
                if (mPlayOnlineHander3 != null) mPlayOnlineHander3.sendMessage(msg);
            }
        }
    };


    private IMediaPlayListener iMediaPlayListener4 = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, PlayStatusType type, int code) {
            Message msg = Message.obtain();
            msg.obj = winIndex;
            if (type == PlayStatusType.eStreamPlayed) {
                msg.what = KEY_Handler_Stream_Played;
                if (mPlayOnlineHander4 != null) mPlayOnlineHander4.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                msg.what = KEY_Handler_First_Frame;
                if (mPlayOnlineHander4 != null) mPlayOnlineHander4.sendMessage(msg);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                msg.what = KEY_Handler_Net_Error;
                if (mPlayOnlineHander4 != null) mPlayOnlineHander4.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFailed) {
                msg.what = KEY_Handler_Play_Failed;
                if (mPlayOnlineHander4 != null) mPlayOnlineHander4.sendMessage(msg);
            }
        }
    };

    public boolean openAudio(int winIndex) {

        return mPlayManager1.openAudio(winIndex) == Err.OK;
    }


    /*****
     *
     *   窗口操作1
     */


    private IOperationListener iOperationListener = new IOperationListener() {
        @Override
        public void onWindowSelected(int position) {
            Log.d(TAG, "onWindowSelected" + position);
        }

        @Override
        public void onPageChange(int newPage, int prePage, int type) {
            Log.d(TAG, "onPageChange" + newPage + prePage + type);
            if (type == 0) {
                if (mPlayManager1.getPageCellNumber() == 1) {
                    mPlayManager1.setEZoomEnable(prePage, false);
                    mPlayManager1.setEZoomEnable(newPage, true);
                }
            }
        }

        @Override
        public void onSplitNumber(int nCurCellNumber, int nCurPage, int nPreCellNumber, int nPrePage) {
            Log.d(TAG, "onSplitNumber" + nCurCellNumber);
        }

        @Override
        public void onControlClick(int nWinIndex, ControlType type) {
            Log.d(TAG, "onControlClick" + type);
            if (type == ControlType.Control_Reflash) {
                startPlay(nWinIndex, mPlayManager1);
            }
        }

        @Override
        public void onSelectWinIndexChange(int newWinIndex, int oldWinIndex) {
            Log.d(TAG, "onSelectWinIndexChange:" + newWinIndex + ":" + oldWinIndex);
            if (!mPlayManager1.hasTalking()) {
                if (mPlayManager1.isOpenAudio(oldWinIndex)) {
                    mPlayManager1.closeAudio(oldWinIndex);
                    mPlayManager1.setNeedOpenAudio(oldWinIndex, true);
                }

                if (mPlayManager1.isPlaying(newWinIndex) && mPlayManager1.isNeedOpenAudio(newWinIndex))
                    mPlayManager1.openAudio(newWinIndex);
            }
        }

        @Override
        public void onWindowDBClick(int winIndex, int type) {
            Log.d(TAG, "onWindowDBClick" + type + " winIndex:" + winIndex + " isWindowMax:" + mPlayManager1.isWindowMax(winIndex));
            if (mPlayManager1.isOpenPTZ(winIndex)) {
                if (mPlayManager1.setPTZEnable(winIndex, false) == Err.OK) {
                    mPlayManager1.setResumeFlag(winIndex, false);
                }
            }
            mPlayManager1.setEZoomEnable(winIndex, type == 0);
        }

        @Override
        public void onMoveWindowBegin(int winIndex) {
            Log.d(TAG, "onMoveWindowBegin");
        }

        @Override
        public void onMovingWindow(int winIndex, float x, float y) {
            Log.d(TAG, "onMovingWindow x:" + x + " y:" + y);
        }

        @Override
        public boolean onMoveWindowEnd(int winIndex, float x, float y) {
            Log.d(TAG, "onMoveWindowEnd x:" + x + " y:" + y);
            return false;
        }
    };


    /*****
     *
     *   窗口操作2
     */


    private IOperationListener iOperationListener2 = new IOperationListener() {
        @Override
        public void onWindowSelected(int position) {
            Log.d(TAG, "onWindowSelected" + position);
        }

        @Override
        public void onPageChange(int newPage, int prePage, int type) {
            Log.d(TAG, "onPageChange" + newPage + prePage + type);
            if (type == 0) {
                if (mPlayManager2.getPageCellNumber() == 1) {
                    mPlayManager2.setEZoomEnable(prePage, false);
                    mPlayManager2.setEZoomEnable(newPage, true);
                }
            }
        }

        @Override
        public void onSplitNumber(int nCurCellNumber, int nCurPage, int nPreCellNumber, int nPrePage) {
            Log.d(TAG, "onSplitNumber" + nCurCellNumber);
        }

        @Override
        public void onControlClick(int nWinIndex, ControlType type) {
            Log.d(TAG, "onControlClick" + type);
            if (type == ControlType.Control_Reflash) {
                startPlay(nWinIndex, mPlayManager2);
            }
        }

        @Override
        public void onSelectWinIndexChange(int newWinIndex, int oldWinIndex) {
            Log.d(TAG, "onSelectWinIndexChange:" + newWinIndex + ":" + oldWinIndex);
            if (!mPlayManager2.hasTalking()) {
                if (mPlayManager2.isOpenAudio(oldWinIndex)) {
                    mPlayManager2.closeAudio(oldWinIndex);
                    mPlayManager2.setNeedOpenAudio(oldWinIndex, true);
                }

                if (mPlayManager2.isPlaying(newWinIndex) && mPlayManager2.isNeedOpenAudio(newWinIndex))
                    mPlayManager2.openAudio(newWinIndex);
            }
        }

        @Override
        public void onWindowDBClick(int winIndex, int type) {
            Log.d(TAG, "onWindowDBClick" + type + " winIndex:" + winIndex + " isWindowMax:" + mPlayManager2.isWindowMax(winIndex));
            if (mPlayManager2.isOpenPTZ(winIndex)) {
                if (mPlayManager2.setPTZEnable(winIndex, false) == Err.OK) {
                    mPlayManager2.setResumeFlag(winIndex, false);
                }
            }
            mPlayManager2.setEZoomEnable(winIndex, type == 0);
        }

        @Override
        public void onMoveWindowBegin(int winIndex) {
            Log.d(TAG, "onMoveWindowBegin");
        }

        @Override
        public void onMovingWindow(int winIndex, float x, float y) {
            Log.d(TAG, "onMovingWindow x:" + x + " y:" + y);
        }

        @Override
        public boolean onMoveWindowEnd(int winIndex, float x, float y) {
            Log.d(TAG, "onMoveWindowEnd x:" + x + " y:" + y);
            return false;
        }
    };

    /*****
     *
     *   窗口操作3
     */


    private IOperationListener iOperationListener3 = new IOperationListener() {
        @Override
        public void onWindowSelected(int position) {
            Log.d(TAG, "onWindowSelected" + position);
        }

        @Override
        public void onPageChange(int newPage, int prePage, int type) {
            Log.d(TAG, "onPageChange" + newPage + prePage + type);
            if (type == 0) {
                if (mPlayManager3.getPageCellNumber() == 1) {
                    mPlayManager3.setEZoomEnable(prePage, false);
                    mPlayManager3.setEZoomEnable(newPage, true);
                }
            }
        }

        @Override
        public void onSplitNumber(int nCurCellNumber, int nCurPage, int nPreCellNumber, int nPrePage) {
            Log.d(TAG, "onSplitNumber" + nCurCellNumber);
        }

        @Override
        public void onControlClick(int nWinIndex, ControlType type) {
            Log.d(TAG, "onControlClick" + type);
            if (type == ControlType.Control_Reflash) {
                startPlay(nWinIndex, mPlayManager3);
            }
        }

        @Override
        public void onSelectWinIndexChange(int newWinIndex, int oldWinIndex) {
            Log.d(TAG, "onSelectWinIndexChange:" + newWinIndex + ":" + oldWinIndex);
            if (!mPlayManager3.hasTalking()) {
                if (mPlayManager3.isOpenAudio(oldWinIndex)) {
                    mPlayManager3.closeAudio(oldWinIndex);
                    mPlayManager3.setNeedOpenAudio(oldWinIndex, true);
                }

                if (mPlayManager3.isPlaying(newWinIndex) && mPlayManager3.isNeedOpenAudio(newWinIndex))
                    mPlayManager3.openAudio(newWinIndex);
            }
        }

        @Override
        public void onWindowDBClick(int winIndex, int type) {
            Log.d(TAG, "onWindowDBClick" + type + " winIndex:" + winIndex + " isWindowMax:" + mPlayManager3.isWindowMax(winIndex));
            if (mPlayManager3.isOpenPTZ(winIndex)) {
                if (mPlayManager3.setPTZEnable(winIndex, false) == Err.OK) {
                    mPlayManager3.setResumeFlag(winIndex, false);
                }
            }
            mPlayManager3.setEZoomEnable(winIndex, type == 0);
        }

        @Override
        public void onMoveWindowBegin(int winIndex) {
            Log.d(TAG, "onMoveWindowBegin");
        }

        @Override
        public void onMovingWindow(int winIndex, float x, float y) {
            Log.d(TAG, "onMovingWindow x:" + x + " y:" + y);
        }

        @Override
        public boolean onMoveWindowEnd(int winIndex, float x, float y) {
            Log.d(TAG, "onMoveWindowEnd x:" + x + " y:" + y);
            return false;
        }
    };

    /*****
     *
     *   窗口操作
     */


    private IOperationListener iOperationListener4 = new IOperationListener() {
        @Override
        public void onWindowSelected(int position) {
            Log.d(TAG, "onWindowSelected" + position);
        }

        @Override
        public void onPageChange(int newPage, int prePage, int type) {
            Log.d(TAG, "onPageChange" + newPage + prePage + type);
            if (type == 0) {
                if (mPlayManager4.getPageCellNumber() == 1) {
                    mPlayManager4.setEZoomEnable(prePage, false);
                    mPlayManager4.setEZoomEnable(newPage, true);
                }
            }
        }

        @Override
        public void onSplitNumber(int nCurCellNumber, int nCurPage, int nPreCellNumber, int nPrePage) {
            Log.d(TAG, "onSplitNumber" + nCurCellNumber);
        }

        @Override
        public void onControlClick(int nWinIndex, ControlType type) {
            Log.d(TAG, "onControlClick" + type);
            if (type == ControlType.Control_Reflash) {
                startPlay(nWinIndex, mPlayManager4);
            }
        }

        @Override
        public void onSelectWinIndexChange(int newWinIndex, int oldWinIndex) {
            Log.d(TAG, "onSelectWinIndexChange:" + newWinIndex + ":" + oldWinIndex);
            if (!mPlayManager4.hasTalking()) {
                if (mPlayManager4.isOpenAudio(oldWinIndex)) {
                    mPlayManager4.closeAudio(oldWinIndex);
                    mPlayManager4.setNeedOpenAudio(oldWinIndex, true);
                }

                if (mPlayManager4.isPlaying(newWinIndex) && mPlayManager4.isNeedOpenAudio(newWinIndex))
                    mPlayManager4.openAudio(newWinIndex);
            }
        }

        @Override
        public void onWindowDBClick(int winIndex, int type) {
            Log.d(TAG, "onWindowDBClick" + type + " winIndex:" + winIndex + " isWindowMax:" + mPlayManager4.isWindowMax(winIndex));
            if (mPlayManager4.isOpenPTZ(winIndex)) {
                if (mPlayManager4.setPTZEnable(winIndex, false) == Err.OK) {
                    mPlayManager4.setResumeFlag(winIndex, false);
                }
            }
            mPlayManager4.setEZoomEnable(winIndex, type == 0);
        }

        @Override
        public void onMoveWindowBegin(int winIndex) {
            Log.d(TAG, "onMoveWindowBegin");
        }

        @Override
        public void onMovingWindow(int winIndex, float x, float y) {
            Log.d(TAG, "onMovingWindow x:" + x + " y:" + y);
        }

        @Override
        public boolean onMoveWindowEnd(int winIndex, float x, float y) {
            Log.d(TAG, "onMoveWindowEnd x:" + x + " y:" + y);
            return false;
        }
    };


    /***
     *   云台监听1
     */
    private IPTZListener iptzListener1 = new IPTZListener() {
        @Override
        public void onPTZControl(int winIndex, PtzOperation oprType, boolean isStop, boolean isLongPress) {
            sendPTZOperation(getPtzOperation(oprType), isStop, channelInfo1);
        }

        @Override
        public void onPTZZooming(int winIndex, float scale, PtzOperation oprType, PtzZoomState state) {

        }
    };
    /***
     *   云台监听1
     */
    private IPTZListener iptzListener2 = new IPTZListener() {
        @Override
        public void onPTZControl(int winIndex, PtzOperation oprType, boolean isStop, boolean isLongPress) {
            sendPTZOperation(getPtzOperation(oprType), isStop, channelInfo2);
        }

        @Override
        public void onPTZZooming(int winIndex, float scale, PtzOperation oprType, PtzZoomState state) {

        }
    };
    /***
     *   云台监听1
     */
    private IPTZListener iptzListener3 = new IPTZListener() {
        @Override
        public void onPTZControl(int winIndex, PtzOperation oprType, boolean isStop, boolean isLongPress) {
            sendPTZOperation(getPtzOperation(oprType), isStop, channelInfo3);
        }

        @Override
        public void onPTZZooming(int winIndex, float scale, PtzOperation oprType, PtzZoomState state) {

        }
    };

    /***
     *   云台监听1
     */
    private IPTZListener iptzListener4 = new IPTZListener() {
        @Override
        public void onPTZControl(int winIndex, PtzOperation oprType, boolean isStop, boolean isLongPress) {
            sendPTZOperation(getPtzOperation(oprType), isStop, channelInfo4);
        }

        @Override
        public void onPTZZooming(int winIndex, float scale, PtzOperation oprType, PtzZoomState state) {

        }
    };

    /**
     * 云台控制
     */
    protected void sendPTZOperation(final ChannelInfo.PtzOperation operation, final boolean isStop, ChannelInfo mChannelInfo) {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<Integer>() {
            @Override
            public Integer doInBackground() throws Exception {
                /**
                 * var1 操作类型（变焦、光圈、焦距...）
                 * var2 uuid
                 * var3 云台步长
                 * var4 操作是否结束
                 */
                return DataAdapterImpl.getInstance().operatePTZ(operation, mChannelInfo.getUuid(), 4, isStop);
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<Integer>() {
            @Override
            public void onSuccess(Integer integer) {

            }

            @Override
            public void onError(BusinessException e) {

            }
        });
    }

    public ChannelInfo.PtzOperation getPtzOperation(PtzOperation oprType) {
        ChannelInfo.PtzOperation operation = ChannelInfo.PtzOperation.stop;
        if (oprType == PtzOperation.up) operation = ChannelInfo.PtzOperation.up;
        if (oprType == PtzOperation.down) operation = ChannelInfo.PtzOperation.down;
        if (oprType == PtzOperation.left) operation = ChannelInfo.PtzOperation.left;
        if (oprType == PtzOperation.right) operation = ChannelInfo.PtzOperation.right;
        if (oprType == PtzOperation.leftUp) operation = ChannelInfo.PtzOperation.leftUp;
        if (oprType == PtzOperation.leftDown) operation = ChannelInfo.PtzOperation.leftDown;
        if (oprType == PtzOperation.rightUp) operation = ChannelInfo.PtzOperation.rightUp;
        if (oprType == PtzOperation.rightDown) operation = ChannelInfo.PtzOperation.rightDown;
        return operation;
        // 若想用摄像头的放大和缩小，operation可以按如下设置：
        // operation = ChannelInfo.PtzOperation.zoomAdd; 放大
        // operation = ChannelInfo.PtzOperation.zoomReduce;缩小
    }


    /**
     * 切换横竖屏
     */
    public void switchScreen() {
        if (isFull) {
            isFull = false;
            linear_title.setVisibility(View.VISIBLE);
//            linear_content.setVisibility(View.GONE);
//            bottm_control.setVisibility(View.GONE);

//            iv_full_screen.setImageResource(R.mipmap.icon_full_screen);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            isFull = true;
            linear_title.setVisibility(View.GONE);
//            linear_content.setVisibility(View.GONE);
//            bottm_control.setVisibility(View.GONE);
//            iv_full_screen.setImageResource(R.mipmap.icon_exit_full_screen);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
//        initCommonWindow();
    }


//    private void postDataWithParame( String xiaodui) {
//
//        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
//        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式，
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("xiaodui", xiaodui);
//
//
//        final Gson gson = new Gson();
//
//        RequestBody body = RequestBody.create(JSON, gson.toJson(map));
//        Request request = new Request.Builder()
//
//                .url("http://baihu.citymishu.com:8441/fuwuqi/wangye/")
//                .get(body)
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//                Log.e("MainActivity", "IOException=" + e.toString());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String string = response.body().string();
//                Log.e("MainActivity", "string=" +string);
//
//            }
//        });
//    }


    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}